package com.example.gui;

import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.example.data.AllData;

public class LoginActivity extends AppCompatActivity {

    private EditText phoneNumberEditText;
    private EditText passwordEditText;
    private Button loginButton;
    private TextView authCodeLoginTextView;
    private TextView registerTextView;

    private String phoneNumber = "";
    private String password = "";
    private boolean isRegisterMode = false;

    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        phoneNumberEditText = findViewById(R.id.phoneNumberEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);
        authCodeLoginTextView = findViewById(R.id.authCodeLoginTextView);
        registerTextView = findViewById(R.id.registerTextView);

        // 获取SharedPreferences对象
        sharedPreferences = getSharedPreferences("UserData", MODE_PRIVATE);

        // 读取保存的手机号和密码
        phoneNumber = sharedPreferences.getString("phoneNumber", "");
        password = sharedPreferences.getString("password", "");

        // 设置手机号和密码输入框的内容
        // 判断是否填写了手机号和密码
        boolean isFilled = !phoneNumber.isEmpty() && !password.isEmpty();

        // 设置登录按钮是否可点击
        loginButton.setEnabled(isFilled);

        phoneNumberEditText.setText(phoneNumber);
        passwordEditText.setText(password);

        // 监听手机号和密码输入框的变化
        phoneNumberEditText.addTextChangedListener(textWatcher);
        passwordEditText.addTextChangedListener(textWatcher);

        // 登录按钮点击事件
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isRegisterMode) {
                    // 注册模式，保存手机号和密码到SharedPreferences中
                    saveRegisterInfo();
                    showRegisterSuccessDialog();
                } else {
                    // 登录模式，判断登录是否成功
                    if (checkLogin()) {
                        // 登录成功，将用户数据存储到AllData中，并跳转到首页
                        saveUserDataToAllData();
                        goToHomePage();
                    } else {
                        // 登录失败，显示提示信息
                        Toast.makeText(LoginActivity.this, "登录失败，请检查手机号和密码", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        // 注册文本点击事件，切换注册/登录模式
        registerTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchRegisterMode();
            }
        });
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            // 获取手机号和密码输入框的内容
            phoneNumber = phoneNumberEditText.getText().toString().trim();
            password = passwordEditText.getText().toString().trim();

            // 判断是否填写了手机号和密码
            boolean isFilled = !phoneNumber.isEmpty() && !password.isEmpty();

            // 设置登录按钮是否可点击
            loginButton.setEnabled(isFilled);
        }
    };

    private void saveRegisterInfo() {
        // 将手机号和密码保存到SharedPreferences中
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("phoneNumber", phoneNumber);
        editor.putString("password", password);
        editor.apply();
    }

    private boolean checkLogin() {
        // 在此处根据SharedPreferences中的数据进行登录验证
        String savedPhoneNumber = sharedPreferences.getString("phoneNumber", "");
        String savedPassword = sharedPreferences.getString("password", "");

        return phoneNumber.equals(savedPhoneNumber) && password.equals(savedPassword);
    }

    private void switchRegisterMode() {
        isRegisterMode = !isRegisterMode;
        if (isRegisterMode) {
            registerTextView.setText("登录");
            loginButton.setText("注册");
        } else {
            registerTextView.setText("注册");
            loginButton.setText("登录");
        }

        // 清空输入框，并重新设置焦点
        phoneNumberEditText.setText("");
        passwordEditText.setText("");
        phoneNumberEditText.requestFocus();
    }

    private void showRegisterSuccessDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setTitle("提示")
                .setMessage("注册成功")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create()
                .show();
    }

    private void saveUserDataToAllData() {
        // 在AllData中保存用户手机号和密码
        AllData data = (AllData) getApplication();
        data.setAccount(phoneNumber);
        data.setPassword(password);
    }

    private void goToHomePage() {
        // 创建一个意图，将登录页(LoginActivity)与主页(HomeActivity)进行关联
        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
        startActivity(intent); // 启动主页
        finish(); // 关闭当前登录页
    }
}
